package cn.zyx.common.utils.file;

import cn.zyx.common.utils.DateUtils;
import cn.zyx.common.utils.snowflake.Seq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/**
 * 文件上传工具类
 */
@Slf4j
public class FileUploadCommonUtils {

    public static final String FILE_URL_PATH = "Path";

    public static final String FILE_URL_APP_PATH = "AppPath";

    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 500 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 返回新的文件流
     * @param file
     * @return
     */
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        return  DateUtils.datePath() + "/" +
                FilenameUtils.getBaseName(file.getOriginalFilename())+ "_" +
                Seq.getId(Seq.uploadSeqType) + "." +
                FileTypeUtils.getExtension(file);
    }
}